import json
import pickle
import sqlite3


class SqliteDB:
    """提供嵌入式数据库得功能，能够实现增，删，查等操作"""

    def __init__(self, db_name):
        self.conn = sqlite3.connect(db_name)
        self.cursor = self.conn.cursor()
        self._create_table()

    def _create_table(self):
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS kvmap (
                uuid TEXT PRIMARY KEY,
                map_info BLOB
            )
        ''')
        self.conn.commit()

    def _serialize(self, data):
        """序列化数据，以存储数据"""
        return pickle.dumps(data)

    def _deserialize(self, blob_data):
        """反序列化数据,以提取数据"""
        return pickle.loads(blob_data)

    def add(self, uuid, data):
        """添加uuid, data到嵌入式数据库中

        这里的添加是一种更新的添加,如果uuid冲突,替换其值为最新的值.
        """
        map_info = self._serialize(data)
        self.cursor.execute('REPLACE INTO kvmap (uuid, map_info) VALUES (?, ?)', (uuid, map_info))
        self.conn.commit()

    def get(self, uuid):
        """
        获取uuid对应的值

        返回值:
            如果存在,返回存储的值
            如果不存在,返回False
        """
        self.cursor.execute('SELECT map_info FROM kvmap WHERE uuid = ?', (uuid,))
        result = self.cursor.fetchone()
        if result:
            return self._deserialize(result[0])
        else:
            return None

    def delete(self, uuid):
        self.cursor.execute('DELETE FROM kvmap WHERE uuid = ?', (uuid,))
        self.conn.commit()

    def clear(self):
        """清空数据"""
        self.cursor.execute(f'DELETE FROM kvmap')
        self.conn.commit()

    def get_all(self):
        """查看数据库的所有值"""
        self.cursor.execute('SELECT uuid, map_info FROM kvmap')
        rows = self.cursor.fetchall()
        if rows:
            data_dict = {}
            for row in rows:
                data_dict[row[0]] = self._deserialize(row[1])
            return data_dict
        else:
            return False


    def show(self):
        """输出当前的所有数据"""
        print(self.get_all())

    def close(self):
        self.conn.close()





# Example usage:
if __name__ == "__main__":
    store = SqliteDB('example.db')

    uuid = '4F909471-32BE-7C54-BE32-1D05C47CA876'
    data = {'key1': 'value1', 'key2': 'value2','key3':['11212']}
    data2 = {'key1': 'val'}
    store.add(uuid, data)
    print(store.get_all())

    store.delete(uuid)
    store.delete(uuid)

    print(store.get_all())
    # store.add(uuid, data2)
    # print(store.get(uuid),type(store.get(uuid).get('key3')))
    # print(store.get('uuid'))

    store.close()